package com.drd.dt.back.service.Impl;

import com.drd.dt.back.dao.BackCommonMapper;
import com.drd.dt.back.dto.JGPushDTO;
import com.drd.dt.back.dto.MessageCenterDTO;
import com.drd.dt.back.service.IFinanceManageService;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.service.impl.TradeServiceImpl;
import com.drd.dt.modular.service.impl.UserMoneyServiceImpl;
import com.drd.dt.util.JgPushUtil;
import com.drd.dt.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 86514 on 2019/4/10.
 */
@Transactional
@Service("financeManageService")
public class FinanceManageServiceImpl implements IFinanceManageService {
    @Autowired
    private UserMoneyServiceImpl moneyService;
    @Autowired
    private BackCommonMapper backCommonMapper;
    @Autowired
    private TradeServiceImpl tradeService;


    /**
     * 获取财务管理列表
     **/
    @Override
    public Tip financeManageList(@RequestParam Map<Object, Object> map) throws Exception{
        List<Map> result = backCommonMapper.getFinanceList(map);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),result);
    }

    /**
     * 审核提现申请
     * @param map
     * @return
     */
    @Override
    public Tip auditing(Map<String, String> map) throws Exception{
        String id = map.get("id");
        String money = map.get("money");//提现金额
        //type  1:通过   0：拒绝  -2取消
        Integer type = Integer.valueOf(map.get("type"));
        //提现类型(1普通佣金  2奖励金  3活动佣金)
        Integer txType = Integer.valueOf(map.get("txType"));
        String reason = "";
        if (type == 0){
            reason = map.get("reason");//拒绝理由
        }
        Map detail = backCommonMapper.getTxStatus(id);
        Integer status = Integer.valueOf(detail.get("status").toString());
        Integer user_id = Integer.valueOf(detail.get("user_id").toString());
        String txid = detail.get("txid").toString();
        String alipay_account = detail.get("alipay_account").toString();
        String alipay_name = detail.get("alipay_name").toString();
        String final_money = detail.get("final_money").toString();//提现金额
        if (!Double.valueOf(money).equals(Double.valueOf(final_money))){
            return ResultUtil.result(BizExceptionEnum.TX_MONEY_ERROR.getCode(), BizExceptionEnum.TX_MONEY_ERROR.getMessage());
        }
        if (status == 0){
            MessageCenterDTO messageCenterDTO = new MessageCenterDTO();
            messageCenterDTO.setTitle(Constant.TX_WITHDRAW_TITLE);
            map.put("approved_time", Constant.y_M_d_H_m_s.format(new Date()));
            String tx_msg = BizExceptionEnum.TX_PUSH_MSG.getMessage();
            if (type == -2){//取消
                map.put("status","-2");
                backCommonMapper.auditing(map);
                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
            } if (type == 0){//拒绝
                tx_msg = BizExceptionEnum.TX_REFUSE.getMessage();
                map.put("status","-1");
                messageCenterDTO.setStatus(0);
                if (!StringUtils.isEmpty(reason)){
                    messageCenterDTO.setContent(reason);
                    tx_msg = reason;
                }else {
                    messageCenterDTO.setContent(tx_msg);
                }
                //拒绝申请后将用户提现金额加上去
                moneyService.txUpdate(user_id,0,Double.parseDouble(money),txType);
            } if (type == 1){//通过
                map.put("status","1");
                tx_msg = Constant.TX_SUCCESS;
                messageCenterDTO.setStatus(1);
                messageCenterDTO.setContent(tx_msg);
                //自动打款
                boolean is_success = tradeService.AliPay(txid, alipay_name, money, alipay_account);
                if (!is_success){//打款失败
                    return ResultUtil.result(BizExceptionEnum.TX_AUTOPAY_ERROR.getCode(), BizExceptionEnum.TX_AUTOPAY_ERROR.getMessage());
                }
            }

            backCommonMapper.auditing(map);

            messageCenterDTO.setUser_id(user_id);
            messageCenterDTO.setCreate_time(Constant.y_M_d_H_m_s.format(new Date()));
            messageCenterDTO.setTx_id(Integer.valueOf(id));
            messageCenterDTO.setHead_pic(Constant.DEFAULT_HEAD_PIC);
            messageCenterDTO.setMoney(Double.valueOf(money));
            //提现结果插入消息中心
            backCommonMapper.insertTxMessage(messageCenterDTO);
            //获取极光key，secret和用户的极光id
            Map jg = backCommonMapper.getJgInfoAndUser(user_id);
            //将提现信息通过极光推送给用户
            if (null != jg){
                String user_jp_id = jg.get("jp_id").toString();
                String deviceT = jg.get("deviceT").toString();//客户端类型（Android:0  IOS:1）
                String masterSecret = jg.get("jg_app_secret").toString();
                String appKey = jg.get("jg_app_key").toString();
//                String appKey = "854b11c346afbecf7f70fec6";
//                String masterSecret = "97047b65df072eaa43d6c007";
                //ios使用券巴士的极光
                String ios_appKey = Constant.QBS_JG_APPKEY;
                String ios_masterSecret = Constant.QBS_JG_APPSECRET;
                if (!StringUtils.isEmpty(user_jp_id) && !StringUtils.isEmpty(deviceT)){
                    Integer dev = Integer.valueOf(deviceT);//客户端类型（Android:0  IOS:1）
                    JGPushDTO dto = new JGPushDTO();
                    dto.setJump_action(2);
                    dto.setIs_login(1);
                    if (dev == 0){
                        JgPushUtil.pushMsg(tx_msg, dto,appKey,masterSecret,user_jp_id);
                    }else if (dev == 1){
                        JgPushUtil.pushMsg(tx_msg,dto,ios_appKey,ios_masterSecret,user_jp_id);
                    }
                }
            }
        }else {
            throw new BussinessException(BizExceptionEnum.BACK_NOT_NEED_AUDIT);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

}
